//
//  Calculator.swift
//  ProjectDemo
//
//  Created by caoxiaozhu on 2018/8/15.
//  Copyright © 2018年 caoxiaozhu. All rights reserved.
//

import UIKit

class Calculator: UIViewController,UITextFieldDelegate {
    
    var num1 : String = "0"
    var num2 : String = "0"
    var result : Int = 0
    var symbolStr : String?
    var firNumField : UITextField?
    var symbolField : UITextField?
    var secNumField : UITextField?
    var resultField : UITextField?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
}

extension Calculator{
    
    func setupUI(){
        
        view.backgroundColor = UIColor.white
        
        firNumField  = UITextField(frame:CGRect(x: 5, y: 5, width: 100, height: 30), placeHolder: "第一个数")
        firNumField?.delegate = self;
        firNumField?.text = num1
        
        let startSymbleX = (firNumField?.frame.maxX)! + 5
//        let startSymbleY = firNumField.frame
        
        symbolField = UITextField(frame: CGRect(x: startSymbleX, y: 5, width: 30, height: 30), placeHolder: "")
        symbolField?.delegate = self;
        symbolField?.textAlignment = .center
        symbolField?.borderStyle = .bezel
        
        let startSecX = (symbolField?.frame.maxX)! + 5
        secNumField = UITextField(frame:CGRect(x: startSecX, y: 5, width: 100, height: 30), placeHolder: "第二个数")
        secNumField?.delegate = self
        secNumField?.text = num2
        
        //等于
        let startEqualX = (secNumField?.frame.maxX)! + 5
        let equalLabel  = UILabel(frame: CGRect(x: startEqualX, y: 5, width: 10, height: 30))
        equalLabel.text = "="
        
        //结果
        let startResultX = equalLabel.frame.maxX + 5
        resultField = UITextField(frame:CGRect(x: startResultX, y: 5, width: 100, height: 30), placeHolder: "结果为")
        resultField?.delegate = self
        resultField?.text = "0"
        
        view.addSubview(firNumField!)
        view.addSubview(symbolField!)
        view.addSubview(secNumField!)
        view.addSubview(equalLabel)
        view.addSubview(resultField!)
        
    }
}

extension Calculator{
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        
        if  firNumField! == textField {
            num1 = textField.text!
        }else if secNumField! == textField{
            num2 = textField.text!
        }
        
        switch symbolField?.text {
        case "+":
            result = Int(num1)! + Int(num2)!
        case "-":
            result = Int(num1)! - Int(num2)!
        case "*":
            result = Int(num1)! * Int(num2)!
        case "/":
            result = Int(num1)! / Int(num2)!
        case "%":
            if Int(num2) == 0{
                return
            }
            result = Int(num1)! % Int(num2)!
            
        default:
            return
        }
        
        resultField?.text = "\(result)"
    }
}
